package com.zm.zmgz.utils;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/05/14/14:33
 * @Description:io相关工具类
 */
public class IOcjwUtils {
    
    static class People implements Serializable{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "People{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        People people = new People();
        people.setName("陈嘉伟1234.com!");
        // java对象生成byte[]
        byte[] bytes = IOcjwUtils.getBytesByObj(people);
        System.out.println(bytes);
        // byte[]生成java对象
        People p = (People)IOcjwUtils.getObjByBytes(bytes);
        System.out.println(p);
    }

    /***
    * @Description: java对象生成byte[]
    * @Param: 
    * @return: 
    * @Author: cjw
    * @Date: 2020-05-14 14:36:44
    */
    public static byte[] getBytesByObj (Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray ();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return bytes;
    }

    /***
    * @Description: byte[]生成java对象
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-05-14 14:40:49
    */
    public static Object getObjByBytes (byte[] bytes) {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            obj = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }

}
